package com.bw.zg2.widgit

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.bw.zg2.R
import com.bw.zg2.bean.CartBean
import org.greenrobot.eventbus.EventBus

/**
 *
 * @ClassName: PlusAddView
 * @Description: 购物车加减组件
 * @Author: zhangyanchao
 * @CreateDate: 2024/9/27 16:36 PM
 * @Version: 1.0
 */
class PlusAddView : LinearLayout {

    private lateinit var tvJia: TextView
    private lateinit var tvNum: TextView
    private lateinit var tvJian: TextView

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        LayoutInflater.from(context).inflate(R.layout.add_layout, this)
        initView()
        changeNum()
    }


    private fun initView() {
        tvJia = findViewById(R.id.tvJia)
        tvNum = findViewById(R.id.tvNum)
        tvJian = findViewById(R.id.tvJian)
    }


    lateinit var bean: CartBean
    fun setNum(bean: CartBean) {
        this.bean = bean
        tvNum.text = bean.count.toString()

    }

    private fun changeNum() {

        tvJia.setOnClickListener {
            var i = tvNum.text.toString().toInt()
            i++
            if (i > 10) {
                Toast.makeText(context, "库存不足", Toast.LENGTH_SHORT).show()
            } else {
                tvNum.text = i.toString()
                bean.count = i
                EventBus.getDefault().post("cart")
            }

        }
        tvJian.setOnClickListener {
            var i = tvNum.text.toString().toInt()
            i--
            if (i < 1) {
                Toast.makeText(context, "不能再少了", Toast.LENGTH_SHORT).show()
            } else {
                tvNum.text = i.toString()
                bean.count = i
                EventBus.getDefault().post("cart")
            }

        }

    }

}
